﻿using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Topro.Admin.Controllers
{
    using Topro.Entity;
    using Topro.Util;

    #region 基础控制
    /// <summary>
    /// 基础控制
    /// </summary>
    public class BaseController : Controller
    {
        #region 注入
        /// <summary>
        /// 用户编号
        /// </summary>
        public int UserId;

        /// <summary>
        /// Ip
        /// </summary>
        public string Ip;

        /// <summary>
        /// 用户名称
        /// </summary>
        public string UserName;

        /// <summary>
        /// 功能权限
        /// </summary>
        public List<string> UserPermissions;
        #endregion

        /// <summary>
        /// OnActionExecuting
        /// </summary>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var isAjaxRequest = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";

            //获取ip地址
            this.Ip = context.HttpContext.Connection.RemoteIpAddress.ToString().Replace("::ffff:","");

            if (HttpContext.User.Claims != null && HttpContext.User.Identity.IsAuthenticated && HttpContext.User.Claims.Count() == 3)
            {
                var permissions = EncryptionUtil.DeCryptDES(string.Join(", ", HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role).Value));
                //获取用户编号
                this.UserId = int.Parse(HttpContext.User.Claims.First().Value);
                this.UserName = HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
                this.UserPermissions = new List<string>(permissions.Split(','));
            }
            else
            {
                if (isAjaxRequest)
                {
                    context.Result = Json(new
                    {
                        IsLogout = true,
                        Message = "登录超时，请重新登录",
                    });
                }
                else
                {
                    context.Result = new ViewResult { ViewName = "~/Views/Account/Index.cshtml" };
                }
            }

            base.OnActionExecuting(context);
        }
    }
    #endregion

    #region 自定义方法拦截器
    /// <summary>
    /// 自定义方法拦截器
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AuthFilter : ActionFilterAttribute
    {
        /// <summary>
        /// 授权码列表
        /// </summary>
        public AuthCode[] Code { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="code">权限码</param>
        public AuthFilter(params AuthCode[] code)
        {
            this.Code = code;
        }

        /// <summary>
        /// 调用后执行
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var isAjaxRequest = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";

            if (context.HttpContext.User.Claims != null && context.HttpContext.User.Claims.Any() && context.HttpContext.User.Claims.Count() == 3)
            {
                var userId = context.HttpContext.User.Claims.First().Value;
                if (!string.IsNullOrEmpty(userId))
                {
                    try
                    {
                        var permissions = EncryptionUtil.DeCryptDES(context.HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role).Value);
                        if (!string.IsNullOrEmpty(permissions))
                        {
                            var isAuthority = Code.Any(item => permissions.Contains(item.ToString()));
                            if (!isAuthority)
                            {
                                if (isAjaxRequest)
                                {
                                    var result = new JsonResult(new JResult
                                    {
                                        Success = false,
                                        Message = "您没有权限访问"
                                    });
                                    context.Result = result;
                                }
                                else
                                {
                                    context.Result = new ViewResult { ViewName = "ErrorPrivilege" };
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (isAjaxRequest)
                        {
                            var result = new JsonResult(new JResult
                            {
                                Success = false,
                                Message = $"您没有权限访问 {ex.Message}"
                            });
                            context.Result = result;
                        }
                        else
                        {
                            context.Result = new ViewResult { ViewName = "ErrorPrivilege" };
                        }
                    }
                }
            }
        }
    }
    #endregion
}
